package com.ruoyi.web.controller.tool;

import com.ruoyi.ai.domain.SysAiTasks;
import com.ruoyi.ai.service.ISysAiPromptService;
import com.ruoyi.ai.service.ISysAiTasksService;
import com.ruoyi.qywx.domain.SysQywxChatdata;
import com.ruoyi.qywx.service.ISysQywxChatdataService;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

import com.alibaba.fastjson2.JSON;
import com.qq.weixin.mp.aes.WXBizJsonMsgCrypt;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.service.ISysAIService;
import com.ruoyi.system.service.impl.SysAIServiceImpl;
import com.tencent.wework.Finance;
import io.swagger.annotations.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * swagger 用户测试方法
 *
 * @author ruoyi
 */
@Api("用户信息管理")
@RestController
@RequestMapping("/qywx")
public class QYWXController extends BaseController
{
    @Autowired
    private ISysAIService sysAIService;// = new SysAIServiceImpl();
    //@Autowired
    //private ISysAiPromptService sysAiPromptService;


    @Value(value = "${qywx.corpID}")
    private String corpID;

    @Value(value = "${qywx.agentId}")
    private String agentId;

    @Value(value = "${qywx.secret}")
    private String secret;

    @Value(value = "${qywx.token}")
    private String token;

    @Value(value = "${qywx.encodingAESKey}")
    private String encodingAESKey;

    @Value(value = "${qywx.financeSecret}")
    private String financeSecret;


    private String priKey = "-----BEGIN RSA PRIVATE KEY-----\n" +
            "MIIEpAIBAAKCAQEAq3DdWjK4Fgf0IZRRM5q7iqX+n509Jv+3/u8ZgOopUK1u6fL3\n" +
            "eqj+PXf/5RKYv5Mc6cQvYJ04D9O4dxZq7goVDRf1FYIUydzqW7kDjsBU3RX4TynQ\n" +
            "zsiv2dm3PCTO2sFxI/BoQqzVO1fQhFunxnaljjbn0JPWpBAxqlOBXBYjO+mMr93j\n" +
            "VVk+JZzsgrLG3rhSV+HNZYNi3l/70JFfxKYTIlAR8NuWpbNFTkETQx48ZNuKFkrY\n" +
            "kYoqSvuTkISt/3V1vgMqJP1yT79Kz8qD+rFzLfR5HBjdjRPOPTn4KgWcScacnPSa\n" +
            "JcBr0CxYN+k1J2+vNYu81N5Ma6NviHxOpnNQ3QIDAQABAoIBAEZYYksfYo+Ppemd\n" +
            "XRBKnkdOw0KlFzGIXewaGaHe8yLqdwdBrbBD5UY9ld9dmRWKfKOi3znKaPV9j0Q2\n" +
            "C5wuwOKFgQfZP0RxBCysprwNSQUKfb+lzcr7Z8SA5AGmrMXv98eiXnV1S201JBcb\n" +
            "MKVri5TmDIp2Du10w5w69Wpenwh2qVnv94xOXv3/uzaW6pb+vTzYb7f67keP6L33\n" +
            "tGoogULH8Fjc2uUWdf8MLnH/va0Ko7vlWqgKOVoaqnWUlysUsFGcp1N/W5CzVJNi\n" +
            "fVxQCNEJWaox3s1opWuFOFg5cLYpwlP5yihf5GI4TVI4XoVZwMMiOkIKRP445O7R\n" +
            "ycU7/uECgYEA0jtE8i5lXl+u8G/8gyGoLc+OppZKwAJ1IU3PVyBeE2jKBoudXomI\n" +
            "ab/oDf4zIk0umLySoQRUlN18G/9QYU2x+z4ZZqxkqpqvPrdiD223H+SqyJuM1PLV\n" +
            "m+q/FOsG1UmDZZ0nLJvrYAFXv0JmokKNQnCufR53SLskn8cbmtY9rvUCgYEA0MOy\n" +
            "A0j1YotxIQROnp3QyRQjKnYNMb+OR23lQ2jSFM7/ppJsMXJWmdDyhkWXrph++5a7\n" +
            "XOKMBVJY0gN4qhtejdnM6Mc3Gu4H5UQuEnMqY+D6AEiJSEm/cMffnoIQqAbpmWZK\n" +
            "7+l84m7uCgDGakjoWF5wiYlxwKewxURkuUScmUkCgYEArQR6SZZFdtXoc5i2iHU6\n" +
            "o/kdvZwTCNL88tvGuD27Lt4e5iQg75zg16dIo7uA+cnrf2gyhLG7qohdi+0jifEX\n" +
            "eV4yKX3Xm1CSyVrDKU9yVp0qsM7TqK3xftBDUkPa684EhaxAgUYRAIIaZR2Quhlr\n" +
            "iDKUaASaxxC9o4GKBnQrb8ECgYBRSuMWxGJJbWMwKC01Nt8GbgEDl9Srepw81F5i\n" +
            "UX78+14xzvKyjoOKggLupkragidwcNGk6dL8f4R2w0NJej7nndhdDLY4llgcvt/x\n" +
            "70aifgjb82MB8zXJBQve/WbfB1IPmfW0Vod65RdsbcDVwm43ew73f73791CugGN4\n" +
            "gW85gQKBgQC28qy1UNsWfQLGbpJ4IqCs7X6EtWHqb/cdlA896rHMnbnqVpiSF4tB\n" +
            "eJZ9GySQE2usQor2ccC9coNlZdgahUxhyZdkJjIF859C/88CgSCx3+TwtHyfw8ke\n" +
            "GCj0pv5wZjEVO76rULP6I1nWOq36ca0ffEbzoZQ4N9kZuZq1migruw==\n" +
            "-----END RSA PRIVATE KEY-----";

    @Autowired
    private ISysQywxChatdataService sysQywxChatdataService;

    @Autowired
    private ISysAiTasksService sysAiTasksService;

    @ApiOperation("企业微信回调")
    @GetMapping("/callback")
    public void callback(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //List<AITaskEntity> taskList = new ArrayList<AITaskEntity>(tasks.values());
        logger.info("=========QYWXController get callback===========");
        logger.info(System.getProperty("java.library.path"));

        WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(token, encodingAESKey, corpID);

        String sVerifyMsgSig = request.getParameter("msg_signature");
        String sVerifyTimeStamp = request.getParameter("timestamp");
        String sVerifyNonce = request.getParameter("nonce");
        String sVerifyEchoStr = request.getParameter("echostr");


        // 解析出url上的参数值如下：
        String sEchoStr = "签名验证错误"; //需要返回的明文
        try {
            sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);
            System.out.println("verifyurl echostr: " + sEchoStr);
            // 验证URL成功，将sEchoStr返回
            //HttpUtils.SetResponse(sEchoStr);
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
        }

        // 设置内容类型和字符编码
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        // 获取PrintWriter用于写入响应
        PrintWriter out = response.getWriter();
        // 写入输出内容
        out.print(sEchoStr);
        // 在完成写入后，确保out被关闭
        out.close();

        //return R.ok("test");
    }


    @ApiOperation("企业微信回调")
    @PostMapping("/callback")
    public void postCallback(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //List<AITaskEntity> taskList = new ArrayList<AITaskEntity>(tasks.values());
        logger.info("=========QYWXController post callback===========");

        WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(token, encodingAESKey, corpID);

        String sReqMsgSig = request.getParameter("msg_signature");
        String sReqTimeStamp = request.getParameter("timestamp");
        String sReqNonce = request.getParameter("nonce");
        //String sVerifyEchoStr = request.getParameter("echostr");

        // post请求的密文数据
        // sReqData = HttpUtils.PostData();
        //String sReqData = "{\"tousername\":\"wx5823bf96d3bd56c7\",\"encrypt\":\"CZWs4CWRpI4VolQlvn4dlEC1alN2MUEY2VklGehgBVLBrlVF7SyT+SV+Toj43l4ayJ9UMGKphktKKmP7B2j/P1ey67XB8PBgS7Wr5/8+w/yWriZv3Vmoo/MH3/1HsIWZrPQ3N2mJrelStIfI2Y8kLKXA7EhfZgZX4o+ffdkZDM76SEl79Ib9mw7TGjZ9Aw/x/A2VjNbV1E8BtEbRxYYcQippYNw7hr8sFfa3nW1xLdxokt8QkRX83vK3DFP2F6TQFPL2Tu98UwhcUpPvdJBuu1/yiOQIScppV3eOuLWEsko=\",\"agentid\":\"218\"}";

        StringBuilder stringBuilder = new StringBuilder();
        String line;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);//.append('\n');
        }
        String sReqData = stringBuilder.toString();
        sReqData = XML.toJSONObject(sReqData).get("xml").toString();

        System.out.println("sReqData: " + sReqData);

        String sEchoStr = "签名验证错误";
        try {
            String sMsg = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData);
            // TODO: 解析出明文json标签的内容进行处理
            sMsg = XML.toJSONObject(sMsg).get("xml").toString();
            System.out.println("after decrypt msg: " + sMsg);
            // For example:
            JSONObject json = new JSONObject(sMsg);

            String MsgType = json.getString("MsgType");
            if(MsgType.equals("text")) {
                String Content = json.getString("Content");
                System.out.println("Content：" + Content);
            }else if(MsgType.equals("event")) {
                System.out.println("msgaudit_notify msg: ");
                String Event = json.getString("Event");
                if(Event.equals("msgaudit_notify")) {
                    //立即开始拉取、分析聊天记录
                    //===============================================================
                    System.out.println("testGetChatData ...");
                    this.financeGetChatData();
                }

            }
            sEchoStr = "success";

        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());

            // TODO
            // 解密失败，失败原因请查看异常
            e.printStackTrace();
        }

        // 设置内容类型和字符编码
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        // 获取PrintWriter用于写入响应
        PrintWriter out = response.getWriter();

        System.out.println("sEchoStr：" + sEchoStr);
        // 写入输出内容
        out.print(sEchoStr);
        // 在完成写入后，确保out被关闭
        out.close();

        //return R.ok("test");
    }


    @ApiOperation("企业微信回调")
    @PostMapping("/testGetChatData")
    public void testGetChatData(HttpServletResponse response, HttpServletRequest request) throws Exception {
        System.out.println("testGetChatData ...");
        this.financeGetChatData();
    }

    public void financeGetChatData() throws Exception {
        long ret = 0;
        long sdk = Finance.NewSdk();
        ret = Finance.Init(sdk, corpID, financeSecret);
        if(ret != 0){
            Finance.DestroySdk(sdk);
            System.out.println("init sdk err ret " + ret);
            return;
        }

        //拉取会话存档
        int seq = 0;//从数据库拉取 最大seq
        List<SysQywxChatdata> sysQywxChatdataList = sysQywxChatdataService.selectSysQywxChatdataListTop1(new SysQywxChatdata());
        if(sysQywxChatdataList.size() > 0){
            seq = Integer.parseInt(sysQywxChatdataList.get(0).getSeq().toString());
        }
        int limit = 1000;
        String proxy = "";
        String passwd = "";
        int timeout = 120;

        //每次使用GetChatData拉取存档前需要调用NewSlice获取一个slice，在使用完slice中数据后，还需要调用FreeSlice释放。
        long slice = Finance.NewSlice();
        ret = Finance.GetChatData(sdk, seq, limit, proxy, passwd, timeout, slice);
        if (ret != 0) {
            System.out.println("getchatdata ret " + ret);
            Finance.FreeSlice(slice);
            return;
        }
        String content = Finance.GetContentFromSlice(slice);
        System.out.println("getchatdata :" + content);
        Finance.FreeSlice(slice);

        //开始处理json
        JSONObject json = new JSONObject(content);
        JSONArray chatdata =  json.getJSONArray("chatdata");
        System.out.println("==========================================================================");

        for (Object obj : chatdata) {
            JSONObject chatjson = (JSONObject) obj; // 转换为JSONObject对象
            long chatSeq = chatjson.getLong("seq");
            String msgid = chatjson.getString("msgid");
            int publickey_ver = chatjson.getInt("publickey_ver");
            String encrypt_random_key = chatjson.getString("encrypt_random_key");
            String encrypt_chat_msg = chatjson.getString("encrypt_chat_msg");

            System.out.println("encrypt_random_key: " + encrypt_random_key);
            //System.out.println("encrypt_chat_msg: " + encrypt_chat_msg);

            //解密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

            // 使用PEMParser解析PEM格式的密钥
            Reader reader = new StringReader(priKey);
            PEMParser pemParser = new PEMParser(reader);
            Object object = pemParser.readObject();

            if (Security.getProvider("BC") == null) {
                Security.addProvider(new BouncyCastleProvider());
            }

            PEMKeyPair pemKeyPair = (PEMKeyPair) object;
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            KeyPair keyPair = converter.getKeyPair(pemKeyPair);

            // 对获得的数据进行其他处理
            cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
            byte[] encrypted= Base64.getDecoder().decode(encrypt_random_key);
            byte[] decrypted = cipher.doFinal(encrypted);

            String encrypt_key = new String(decrypted, StandardCharsets.UTF_8);

            //每次使用DecryptData解密会话存档前需要调用NewSlice获取一个slice，在使用完slice中数据后，还需要调用FreeSlice释放。
            long msg = Finance.NewSlice();
            ret = Finance.DecryptData(sdk, encrypt_key, encrypt_chat_msg, msg);
            if (ret != 0) {
                System.out.println("getchatdata ret " + ret);
                Finance.FreeSlice(msg);
                return;
            }
            String decryptedMsgJson = Finance.GetContentFromSlice(msg);
            System.out.println("decrypt ret:" + ret + " msg:" + decryptedMsgJson);
            SysQywxChatdata sysQywxChatdata = new SysQywxChatdata();

            //处理json
            JSONObject msgJson = new JSONObject(decryptedMsgJson); // 转换为JSONObject对象
            try {

                String from = msgJson.getString("from");
                Long msgtime = (new Date()).getTime();
                try{
                    msgtime = msgJson.getLong("msgtime");
                }catch (Exception ex){
                    try{
                        msgtime = msgJson.getLong("time");
                        from = msgJson.getString("user");
                    }catch (Exception ex1){

                    }
                }

                sysQywxChatdata.setSeq(chatSeq);
                sysQywxChatdata.setMsgid(msgid);
                sysQywxChatdata.setPublickeyVer((long) publickey_ver);
                sysQywxChatdata.setEncryptRandomKey(encrypt_random_key);
                sysQywxChatdata.setEncryptChatMsg(encrypt_chat_msg);
                sysQywxChatdata.setDecryptChatMsg(decryptedMsgJson);
                sysQywxChatdata.setMsgtime(msgtime);
                sysQywxChatdataService.insertSysQywxChatdata(sysQywxChatdata);

            }catch (Exception ex){
                System.out.println("insertSysQywxChatdata err " + ex.getMessage());
            }

            Finance.FreeSlice(msg);
        }

        Finance.DestroySdk(sdk);

    }

    ///暂时作废
    public void financeGetChatData2() throws Exception {
        long ret = 0;
        long sdk = Finance.NewSdk();
        ret = Finance.Init(sdk, corpID, financeSecret);
        if(ret != 0){
            Finance.DestroySdk(sdk);
            System.out.println("init sdk err ret " + ret);
            return;
        }

        //拉取会话存档
        int seq = 0;//从数据库拉取 最大seq
        List<SysQywxChatdata> sysQywxChatdataList = sysQywxChatdataService.selectSysQywxChatdataListTop1(new SysQywxChatdata());
        if(sysQywxChatdataList.size() > 0){
            seq = Integer.parseInt(sysQywxChatdataList.get(0).getSeq().toString());
        }
        int limit = 1000;
        String proxy = "";
        String passwd = "";
        int timeout = 120;

        //每次使用GetChatData拉取存档前需要调用NewSlice获取一个slice，在使用完slice中数据后，还需要调用FreeSlice释放。
        long slice = Finance.NewSlice();
        ret = Finance.GetChatData(sdk, seq, limit, proxy, passwd, timeout, slice);
        if (ret != 0) {
            System.out.println("getchatdata ret " + ret);
            Finance.FreeSlice(slice);
            return;
        }
        String content = Finance.GetContentFromSlice(slice);
        System.out.println("getchatdata :" + content);
        Finance.FreeSlice(slice);

        //开始处理json
        JSONObject json = new JSONObject(content);
        JSONArray chatdata =  json.getJSONArray("chatdata");
        System.out.println("==========================================================================");

        for (Object obj : chatdata) {
            JSONObject chatjson = (JSONObject) obj; // 转换为JSONObject对象
            long chatSeq = chatjson.getLong("seq");
            String msgid = chatjson.getString("msgid");
            int publickey_ver = chatjson.getInt("publickey_ver");
            String encrypt_random_key = chatjson.getString("encrypt_random_key");
            String encrypt_chat_msg = chatjson.getString("encrypt_chat_msg");

            System.out.println("encrypt_random_key: " + encrypt_random_key);
            //System.out.println("encrypt_chat_msg: " + encrypt_chat_msg);

            //解密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

            // 使用PEMParser解析PEM格式的密钥
            Reader reader = new StringReader(priKey);
            PEMParser pemParser = new PEMParser(reader);
            Object object = pemParser.readObject();

            if (Security.getProvider("BC") == null) {
                Security.addProvider(new BouncyCastleProvider());
            }

            PEMKeyPair pemKeyPair = (PEMKeyPair) object;
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            KeyPair keyPair = converter.getKeyPair(pemKeyPair);

            // 对获得的数据进行其他处理
            cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
            byte[] encrypted= Base64.getDecoder().decode(encrypt_random_key);
            byte[] decrypted = cipher.doFinal(encrypted);

            String encrypt_key = new String(decrypted, StandardCharsets.UTF_8);

            //每次使用DecryptData解密会话存档前需要调用NewSlice获取一个slice，在使用完slice中数据后，还需要调用FreeSlice释放。
            long msg = Finance.NewSlice();
            ret = Finance.DecryptData(sdk, encrypt_key, encrypt_chat_msg, msg);
            if (ret != 0) {
                System.out.println("getchatdata ret " + ret);
                Finance.FreeSlice(msg);
                return;
            }
            String decryptedMsgJson = Finance.GetContentFromSlice(msg);
            System.out.println("decrypt ret:" + ret + " msg:" + decryptedMsgJson);
            SysQywxChatdata sysQywxChatdata = new SysQywxChatdata();

            //处理json
            JSONObject msgJson = new JSONObject(decryptedMsgJson); // 转换为JSONObject对象
            try {
                sysQywxChatdata.setSeq(chatSeq);
                sysQywxChatdata.setMsgid(msgid);
                sysQywxChatdata.setPublickeyVer((long) publickey_ver);
                sysQywxChatdata.setEncryptRandomKey(encrypt_random_key);
                sysQywxChatdata.setEncryptChatMsg(encrypt_chat_msg);
                sysQywxChatdata.setDecryptChatMsg(decryptedMsgJson);
                sysQywxChatdataService.insertSysQywxChatdata(sysQywxChatdata);

                //插入成功 开始分析任务
                String msgtype = msgJson.getString("msgtype");
                if(msgtype.equals("text")){
                    JSONObject objectContent = msgJson.getJSONObject(msgtype);
                    String objcontent = objectContent.getString("content");
                    System.out.println("objcontent:" + objcontent);
                    String objfrom = "";
                    try {
                        objfrom = msgJson.getString("from");
                        System.out.println("from:" + objfrom);
                    }catch (Exception e1){}

                    //开始大模型分析...
                    try {
                        int i =0;
                        List<SysAiTasks> sysAiTasksList = sysAIService.taskAnalysis(objcontent);
                        System.out.println("from:" + objfrom);
                        System.out.println("sysAiTasksList=======" + JSON.toJSONString(sysAiTasksList));
                        for(int x=0;x<sysAiTasksList.size();x++) {
                        //sysAiTasksList.forEach(task -> {
                            SysAiTasks task = sysAiTasksList.get(x);
                            //if(!"".equals(task.getTaskMemo()) && !"无".equals(task.getTaskMemo()) && task.getTaskMemo()!=null){
                            //    if(!"".equals(task.getTaskDate()) && !"无".equals(task.getTaskDate()) && task.getTaskDate()!=null){
                            task.setTaskCreator(objfrom);
                            task.setRoomid(msgJson.getString("roomid"));
                            task.setMsgtime(msgJson.getLong("msgtime"));
                            task.setOrignalContent(objcontent);
                            task.setOrignalMsg(decryptedMsgJson);

                            System.out.println("task=======" + JSON.toJSONString(task));
                            sysAiTasksService.insertSysAiTasks(task);
                            i=i+1;
                            /*    }else{
                                    System.out.println("SysAiTasks err 没有具体日期 跳过");
                                }
                            }else{
                                System.out.println("SysAiTasks err 没有任务内容 跳过");
                            }*/
                            //});
                        }
                        System.out.println("AtomicInteger i 成功插入任务数: " + i);
                        if(i<=0){
                            System.out.println("一个都没录入重来....... " + i);
                            //一个都没录入重来
                            sysAiTasksList = sysAIService.taskAnalysis(objcontent);
                            System.out.println("from:" + objfrom);
                            System.out.println("sysAiTasksList=======" + JSON.toJSONString(sysAiTasksList));
                            for(int x=0;x<sysAiTasksList.size();x++) {
                                //sysAiTasksList.forEach(task -> {
                                SysAiTasks task = sysAiTasksList.get(x);
                                //if(!"".equals(task.getTaskMemo()) && !"无".equals(task.getTaskMemo()) && task.getTaskMemo()!=null){
                                //if(!"".equals(task.getTaskDate()) && !"无".equals(task.getTaskDate()) && task.getTaskDate()!=null){

                                task.setTaskCreator(objfrom);
                                task.setRoomid(msgJson.getString("roomid"));
                                task.setMsgtime(msgJson.getLong("msgtime"));
                                task.setOrignalContent(objcontent);
                                task.setOrignalMsg(decryptedMsgJson);

                                System.out.println("task=======" + JSON.toJSONString(task));
                                sysAiTasksService.insertSysAiTasks(task);
                                /*    }else{
                                        System.out.println("SysAiTasks err 没有具体日期 跳过");
                                    }
                                }else{
                                    System.out.println("SysAiTasks err 没有任务内容 跳过");
                                }*/
                                //});
                            }
                            System.out.println("AtomicInteger i 成功插入任务数: " + i);
                        }

                    }catch (Exception ex){
                        System.out.println("taskAnalysis err " + ex.toString());
                    }

                }

            }catch (Exception ex){
                System.out.println("insertSysQywxChatdata err " + ex.getMessage());
            }

            Finance.FreeSlice(msg);
        }

        Finance.DestroySdk(sdk);

    }

}

